<?php
/**
 * Created by PhpStorm
 * author  :gogochen
 * date    :2019/12/13
 * time    :14:49
 */

namespace App\Manager;

use App\Model\Player;

/**
 * description  游戏管理
 * Class Logic
 * @package App\Manager
 */
class Logic
{

    /**
     * description  根据玩家id放入DataCenter的匹配队列中
     * @param $playerId
     */
    public function matchPlayer($playerId)
    {
        DataCenter::pushPlayerToWaitList($playerId);
        //发起一个task尝试匹配
        DataCenter::$server->task(['code' => TaskManager::TASK_CODE_FIND_PLAYER]);
    }

    /**
     * description
     * @param $playerId
     * @param $roomId
     */
    public function bindRoomWorker($playerId, $roomId)
    {
        $playerFd = DataCenter::getPlayerFd($playerId);
        DataCenter::$server->bind($playerId, crc32($roomId));
        DataCenter::$server->push($playerId, $roomId);
        Sender::sendMessage($playerId, Sender::MSG_ROOM_ID, ['room_id' => $roomId]);
    }

    /**
     * description  创建房间
     * @param $redPlayer
     * @param $bluePlayer
     */
    public function createRoom($redPlayer, $bluePlayer)
    {
        $roomId = uniqid('room_');
        $this->bindRoomWorker($redPlayer, $roomId);
        $this->bindRoomWorker($bluePlayer, $roomId);
    }

    /**
     * description  游戏房间开始
     * @param $roomId
     * @param $playerId
     */
    public function startRoom($roomId, $playerId)
    {
        if (!isset(DataCenter::$global['rooms'][$roomId])) {
            DataCenter::$global['rooms'][$roomId] = [
                'id' => $roomId,
                'manager' => new Game()
            ];
        }
        /**
         * @var Game $gameManager
         */
        $gameManager = DataCenter::$global['rooms'][$roomId]['manager'];
        if (empty(count($gameManager->getPlayers()))) {
            //第一个玩家
            $gameManager->createPlayer($playerId, 6, 1);
            Sender::sendMessage($playerId, Sender::MSG_WAIT_PLAYER);
        } else {
            //第二个玩家
            $gameManager->createPlayer($playerId, 6, 10);
            Sender::sendMessage($playerId, Sender::MSG_ROOM_START);
            $this->sendGameInfo($roomId);
        }
    }


    /**
     * description  发送游戏数据
     * @param $roomId
     */
    public function sendGameInfo($roomId)
    {
        /**
         * @var Game $gameManager
         * @var Player $player
         */
        $gameManager = DataCenter::$global['rooms'][$roomId]['manager'];
        $players = $gameManager->getPlayers();
        $mapData = $gameManager->getMapData();
        foreach ($players as $player) {
            $data = [
                'players' => $players,
                'map_data' => $mapData
            ];
            Sender::sendMessage($player->getId(), Sender::MSG_GAME_INFO, $data);
        }
    }
}